package com.atguigu.tingshu.user.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import com.atguigu.tingshu.album.AlbumFeignClient;
import com.atguigu.tingshu.common.cache.GuiGuCache;
import com.atguigu.tingshu.common.constant.KafkaConstant;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.service.KafkaService;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.user.*;
import com.atguigu.tingshu.user.mapper.*;
import com.atguigu.tingshu.user.service.UserInfoService;
import com.atguigu.tingshu.user.strategy.ItemTypeStrategy;
import com.atguigu.tingshu.user.strategy.StrategyFactory;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private WxMaService wxMaService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private KafkaService kafkaService;

    @Autowired
    private UserPaidAlbumMapper userPaidAlbumMapper;

    @Autowired
    private UserPaidTrackMapper userPaidTrackMapper;

    @Autowired
    private AlbumFeignClient albumFeignClient;

    @Autowired
    private VipServiceConfigMapper vipServiceConfigMapper;

    @Autowired
    private UserVipServiceMapper userVipServiceMapper;

    /**
     * 小程序端提交临时凭据code，登录（调用微信接口获取微信账号唯一标识：openId）
     *
     * @param code 临时凭据
     * @return 对象，登录登录成功后：token
     */
    @Override
    public Map<String, String> wxLogin(String code) {
        try {
            //1.根据入参提交临时票据，调用微信获取微信账户唯一标识接口，得到微信账户openId
            WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(code);
            if (sessionInfo != null) {
                //2.根据微信唯一标识查询用户记录
                String wxOpenId = sessionInfo.getOpenid();

                //2.1 如果查询为空-将微信OpenId跟听书项目中用户关联（新增用户记录中存储微信账户唯一标识）
                LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(UserInfo::getWxOpenId, wxOpenId);
                UserInfo userInfo = userInfoMapper.selectOne(queryWrapper);
                if (userInfo == null) {
                    //2.2 为首次登录用户构建用户对象，保存用户记录
                    userInfo = new UserInfo();
                    userInfo.setWxOpenId(wxOpenId);
                    userInfo.setNickname("听友" + IdUtil.getSnowflakeNextId());
                    userInfo.setAvatarUrl("https://oss.aliyuncs.com/aliyun_id_photo_bucket/default_handsome.jpg");
                    userInfo.setIsVip(0);
                    userInfoMapper.insert(userInfo);
                    //2.3 发送Kafka异步消息，通知账户微服务新增账户记录
                    kafkaService.sendMessage(KafkaConstant.QUEUE_USER_REGISTER, userInfo.getId().toString());
                }

                //3.基于用户记录生成Token 将用户令牌存入Redis Key:前缀+token  Value:用户信息UserInfoVo
                String token = IdUtil.fastUUID();
                String loginKey = RedisConstant.USER_LOGIN_KEY_PREFIX + token;
                //排除掉用户隐私数据
                UserInfoVo userInfoVo = BeanUtil.copyProperties(userInfo, UserInfoVo.class);
                redisTemplate.opsForValue().set(loginKey, userInfoVo, RedisConstant.USER_LOGIN_KEY_TIMEOUT, TimeUnit.SECONDS);

                //4.将用户token封装结果返回
                Map<String, String> mapResult = new HashMap<>();
                mapResult.put("token", token);
                return mapResult;
            }
            return null;
        } catch (Exception e) {
            log.error("[用户服务]微信登录异常：{}", e);
            throw new RuntimeException(e);
        }
    }

    /**
     * 查询用户基本信息
     *
     * @param userId
     * @return
     */
    @Override
    @GuiGuCache(prefix = "userInfoVo:")
    public UserInfoVo getUserInfo(Long userId) {
        //1.根据主键ID查询用户对象
        UserInfo userInfo = userInfoMapper.selectById(userId);
        //2.将用户PO对象转为VO对象
        return BeanUtil.copyProperties(userInfo, UserInfoVo.class);
    }

    /**
     * 修改用户基本信息（限定只能修改账户昵称、头像）
     * 延时双删方案：保证缓存数据一致性
     *
     * @param userId
     * @param userInfoVo
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateUser(Long userId, UserInfoVo userInfoVo) {
        //1.先删除缓存
        String key = "userInfoVo:" + userId;
        redisTemplate.delete(key);
        //2.执行修改
        UserInfo userInfo = new UserInfo();
        userInfo.setId(userId);
        userInfo.setNickname(userInfoVo.getNickname());
        userInfo.setAvatarUrl(userInfoVo.getAvatarUrl());
        userInfoMapper.updateById(userInfo);

        //3.睡眠时间（确保并发读线程将DB中“脏”数据放入缓存）
        try {
            TimeUnit.MILLISECONDS.sleep(200);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        //4.再删除一次缓存
        redisTemplate.delete(key);
    }

    /**
     * 判断当前用户某一页中声音列表购买情况
     *
     * @param userId               用户ID
     * @param albumId              专辑ID
     * @param needChackTrackIdList 待检查购买情况声音列表
     * @return data:{声音ID：购买结果}   结果：1（已购）0（未购买）
     */
    @Override
    public Map<Long, Integer> userIsPaidTrack(Long userId, Long albumId, List<Long> needChackTrackIdList) {
        //1.根据用户ID+专辑ID查询已购专辑表
        LambdaQueryWrapper<UserPaidAlbum> userPaidAlbumLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userPaidAlbumLambdaQueryWrapper.eq(UserPaidAlbum::getAlbumId, albumId);
        userPaidAlbumLambdaQueryWrapper.eq(UserPaidAlbum::getUserId, userId);
        Long count = userPaidAlbumMapper.selectCount(userPaidAlbumLambdaQueryWrapper);
        if (count > 0) {
            //1.1 存在专辑购买记录-用户购买过该专辑，将待检查声音列表购买情况设置为：1
            Map<Long, Integer> mapResult = new HashMap<>();
            for (Long trackId : needChackTrackIdList) {
                mapResult.put(trackId, 1);
            }
            return mapResult;
        }

        //2. 不存在专辑购买记录-根据用户ID+声音列表查询已购声音表
        LambdaQueryWrapper<UserPaidTrack> userPaidTrackLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userPaidTrackLambdaQueryWrapper.eq(UserPaidTrack::getUserId, userId);
        userPaidTrackLambdaQueryWrapper.in(UserPaidTrack::getTrackId, needChackTrackIdList);
        //获取本页中已购买声音列表
        List<UserPaidTrack> userPaidTrackList = userPaidTrackMapper.selectList(userPaidTrackLambdaQueryWrapper);
        //2.1 不存在声音购买记录-将待检查声音列表购买情况设置为：0
        if (CollectionUtil.isEmpty(userPaidTrackList)) {
            Map<Long, Integer> mapResult = new HashMap<>();
            for (Long trackId : needChackTrackIdList) {
                mapResult.put(trackId, 0);
            }
            return mapResult;
        }
        //2.2 存在声音购买记录-循环判断待检查声音ID找出哪些是已购，哪些是未购买
        List<Long> userPaidTrackIdList = userPaidTrackList.stream().map(UserPaidTrack::getTrackId).collect(Collectors.toList());
        Map<Long, Integer> mapResult = new HashMap<>();
        for (Long needCheckTrackId : needChackTrackIdList) {
            //如果待检查声音ID包含在已购声音Id集合中（已购买）
            if (userPaidTrackIdList.contains(needCheckTrackId)) {
                mapResult.put(needCheckTrackId, 1);
            } else {
                //反之则未购买声音
                mapResult.put(needCheckTrackId, 0);
            }
        }
        return mapResult;
    }

    /**
     * 验证当前用户是否购买过专辑
     *
     * @param albumId
     * @return
     */
    @Override
    public Boolean isPaidAlbum(Long albumId) {
        //1.获取当前用户ID
        Long userId = AuthContextHolder.getUserId();
        //2.构建查询条件：用户ID+专辑ID 查询专辑购买记录表
        LambdaQueryWrapper<UserPaidAlbum> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserPaidAlbum::getUserId, userId);
        queryWrapper.eq(UserPaidAlbum::getAlbumId, albumId);
        Long count = userPaidAlbumMapper.selectCount(queryWrapper);
        return count > 0;
    }

    /**
     * 根据用户ID+专辑ID查询已购声音集合
     *
     * @param userId  用户ID
     * @param albumId 专辑ID
     * @return
     */
    @Override
    public List<Long> getUserPaidTrackIdList(Long userId, Long albumId) {
        //1.根据用户ID+专辑ID查询已购声音集合
        LambdaQueryWrapper<UserPaidTrack> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserPaidTrack::getUserId, userId);
        queryWrapper.eq(UserPaidTrack::getAlbumId, albumId);
        List<UserPaidTrack> userPaidTrackList = userPaidTrackMapper.selectList(queryWrapper);
        if (CollectionUtil.isNotEmpty(userPaidTrackList)) {
            //2.获取已购声音ID集合
            List<Long> userPaidTrackIdList = userPaidTrackList.stream().map(UserPaidTrack::getTrackId).collect(Collectors.toList());
            return userPaidTrackIdList;
        }
        return null;
    }



    //@Autowired
    //private AlbumStrategy albumStrategy;
    //
    //@Autowired
    //private TrackStrategy trackStrategy;
    //
    //@Autowired
    //private VipStrategy vipStrategy;

    @Autowired
    private StrategyFactory strategyFactory;



    /**
     * 处理用户购买记录（虚拟物品发货）
     *
     * @param userPaidRecordVo 购买记录VO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void savePaidRecord(UserPaidRecordVo userPaidRecordVo) {
        ItemTypeStrategy strategy = strategyFactory.getStrategy(userPaidRecordVo.getItemType());
        strategy.savePaidRecord(userPaidRecordVo);

       /* //1.判断购买项目类型-处理专辑
        if (SystemConstant.ORDER_ITEM_TYPE_ALBUM.equals(userPaidRecordVo.getItemType())) {
            //1.1 根据订单编号查询专辑购买记录
            LambdaQueryWrapper<UserPaidAlbum> userPaidAlbumLambdaQueryWrapper = new LambdaQueryWrapper<>();
            userPaidAlbumLambdaQueryWrapper.eq(UserPaidAlbum::getOrderNo, userPaidRecordVo.getOrderNo());
            Long count = userPaidAlbumMapper.selectCount(userPaidAlbumLambdaQueryWrapper);
            if (count > 0) {
                return;
            }
            //1.2 查询到专辑购买记录为空则新增购买记录
            UserPaidAlbum userPaidAlbum = new UserPaidAlbum();
            userPaidAlbum.setOrderNo(userPaidRecordVo.getOrderNo());
            userPaidAlbum.setUserId(userPaidRecordVo.getUserId());
            userPaidAlbum.setAlbumId(userPaidRecordVo.getItemIdList().get(0));
            userPaidAlbumMapper.insert(userPaidAlbum);
        } else if (SystemConstant.ORDER_ITEM_TYPE_TRACK.equals(userPaidRecordVo.getItemType())) {
            //2.判断购买项目类型-处理声音
            //2.1 根据订单编号查询声音购买记录
            LambdaQueryWrapper<UserPaidTrack> userPaidTrackLambdaQueryWrapper = new LambdaQueryWrapper<>();
            userPaidTrackLambdaQueryWrapper.eq(UserPaidTrack::getOrderNo, userPaidRecordVo.getOrderNo());
            Long count = userPaidTrackMapper.selectCount(userPaidTrackLambdaQueryWrapper);
            if (count > 0) {
                return;
            }
            //2.2 查询到声音购买记录为空则新增购买记录（循环批量新增）
            //2.2.1 远程调用专辑服务-根据声音ID查询声音对象-获取声音所属专辑ID
            TrackInfo trackInfo = albumFeignClient.getTrackInfo(userPaidRecordVo.getItemIdList().get(0)).getData();
            Long albumId = trackInfo.getAlbumId();
            //2.2.2 遍历购买项目ID集合批量新增声音购买记录
            userPaidRecordVo.getItemIdList().forEach(trackId -> {
                UserPaidTrack userPaidTrack = new UserPaidTrack();
                userPaidTrack.setOrderNo(userPaidRecordVo.getOrderNo());
                userPaidTrack.setUserId(userPaidRecordVo.getUserId());
                userPaidTrack.setAlbumId(albumId);
                userPaidTrack.setTrackId(trackId);
                userPaidTrackMapper.insert(userPaidTrack);
            });
        } else if (SystemConstant.ORDER_ITEM_TYPE_VIP.equals(userPaidRecordVo.getItemType())) {
            //3.判断购买项目类型-处理VIP会员-允许多次购买
            //3.1 新增VIP购买记录
            UserVipService userVipService = new UserVipService();
            //3.1.1 根据VIP套餐ID查询套餐信息-得到VIP会员服务月数
            Long vipConfigId = userPaidRecordVo.getItemIdList().get(0);
            VipServiceConfig vipServiceConfig = vipServiceConfigMapper.selectById(vipConfigId);
            Integer serviceMonth = vipServiceConfig.getServiceMonth();
            //3.1.2 获取用户身份，如果是VIP会员，则续费
            UserInfo userInfo = userInfoMapper.selectById(userPaidRecordVo.getUserId());
            Integer isVip = userInfo.getIsVip();
            if (isVip.intValue() == 1 && userInfo.getVipExpireTime().after(new Date())) {
                //如果是VIP会员，则续费
                userVipService.setStartTime(userInfo.getVipExpireTime());
                //续费会员过期时间=现有会员过期时间+套餐服务月数
                userVipService.setExpireTime(DateUtil.offsetMonth(userInfo.getVipExpireTime(), serviceMonth));
            } else {
                //3.1.3 获取用户身份，如果是普通用户，则新开
                userVipService.setStartTime(new Date());
                //续费会员过期时间=现有会员过期时间+套餐服务月数
                userVipService.setExpireTime(DateUtil.offsetMonth(new Date(), serviceMonth));
            }
            //3.1.4 构建VIP购买记录对象保存
            userVipService.setUserId(userPaidRecordVo.getUserId());
            userVipService.setOrderNo(userPaidRecordVo.getOrderNo());
            userVipServiceMapper.insert(userVipService);

            //3.2 更新用户表中VIP状态及会员过期时间
            userInfo.setIsVip(1);
            userInfo.setVipExpireTime(userVipService.getExpireTime());
            userInfoMapper.updateById(userInfo);
        }*/
    }

    /**
     * 更新VIP状态：处理过期会员
     * @return
     */
    @Override
    public void updateVipExpireStatus(Date date) {
        userInfoMapper.updateVipExpireStatus(date);
    }
}
